package cn.airfei.netty.nettyexample.rpc.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description:
 * @author: air
 * @create: 2021-01-22 15:51
 */
public class NettyClient {
    // 创建线程池
    private static ExecutorService executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static NettyClientHandler client;

    // 获取代理对象
    public Object getBean(final Class<?> serverClass,final String providerName){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[]{serverClass},(proxy, method, args) -> {
            if (client==null){
                initClient();
            }
            // 设置要发给服务器的信息
            client.setPara(providerName+args[0]);
            return executorService.submit(client).get();
        });

    }


    // 初始化
    private static void initClient() throws InterruptedException {
        client=new NettyClientHandler();

        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(client);
                    }
                });

        ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 7000);
        channelFuture.channel().closeFuture();


    }

    public static void main(String[] args) {

    }

}
